angular.module('dept.controllers', ['dept.services'])

//部门/门店 管理
.controller('DeptsCtrl', function($scope,$ionicModal,deptService) {
	var deptsSubHandle = $scope.subscribe('departments');

	$scope.deptTree=[];
	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			departments: function() {
			  return Departments.find({});
			}
		});
		$scope.autorun(function(){
			if(deptsSubHandle.ready()){
				$scope.deptTree = deptService.getCatTree();
	   			deptService.expendAll($scope.deptTree);
			}
		});
	});
})
// 添加部门
.controller('DeptAddCtrl', function($scope,$ionicModal,$stateParams,$ionicHistory,deptService) {
	var deptsSubHandle = $scope.subscribe('departments');
	var optionsSubHandle = $scope.subscribe('default_options');
	$scope.parentDepts=[];
	$scope.newDept={};
	$scope.newDept.parents=[];
	$scope.isUseParentAddr = true;


	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			departments: function() {
			  return Departments.find({type:{'$not':'柜组'}},{fields:{name:1,type:1}});
			},
			dept_options: function() {
			  return DefaultOptions.findOne({name:'部门'},{fields: {value_set:1}});
			}
		});

		if($stateParams.parent_id){
			$scope.autorun(function(){
				if(deptsSubHandle.ready() && $scope.departments){
					$scope.parentDepts=[{_id:undefined,name:'无'}];
					$scope.departments.forEach(function(dept) {
						$scope.parentDepts.push({'_id':dept._id,'name':dept.name});
				    });
				}
			});
			$scope.newDept.parent_id = $stateParams.parent_id;
		}
	});

	// 部门类型选择操作
	$scope.typeSelect = function(){
		switch($scope.newDept.type){

			case '门店':
				$scope.parentDepts=undefined;
				$scope.newDept.parents=[];
				// $scope.parentDepts=null;
    			var absStore = Departments.findOne({'type':'门店组'});
				if(absStore){
					$scope.newDept.parents.push(absStore._id);
					$scope.newDept.parent_id=absStore._id;

		    	}else{
		    		$scope.newDept.parents =undefined;
		    	}
				break;
			case '售后服务部':
			case '仓库':
			case '销售部':
				// $scope.newDept.parents=[];
				$scope.parentDepts=[{_id:undefined,name:'无'}];
				$scope.departments.forEach(function(dept) {
					if(dept.type=='门店'){
						$scope.parentDepts.push({'_id':dept._id,'name':dept.name});
			    	}
			    });
				break;
			case '柜组':
				// $scope.parentDepts=[];

				var storeC = Departments.findOne({ type: '门店组' },{fields:{_id:1}});
				var parents = Departments.find({ 'parents': storeC._id,type:{'$not':'柜组'} }, {fields:{_id:1,name:1}}).fetch();

			    $scope.parentDepts=parents;
				break;
			case '总经部':
			case '人力资源部':
			case '采购部':
			case '行政部':
			case '财务部':
			case '自定义':
			// default:
				$scope.parentDepts=[{_id:undefined,name:'无'}];
				$scope.departments.forEach(function(dept) {
					$scope.parentDepts.push({'_id':dept._id,'name':dept.name});
			    });
				break;
		}

		$scope.newDept.name = $scope.newDept.type;
	};
	$scope.add = function(){
		// console.log($scope.newDept);
		if (!$scope.newDept.name || !$scope.newDept.type) return;
		if($scope.newDept.parent_id && !$scope.newDept.parents){
			var parent = Departments.find({ _id: $scope.newDept.parent_id });
			if(parent.parents){
				$scope.newDept.parents=parent.parents;
			}
			$scope.newDept.parents.push($scope.newDept.parent_id);
		}

		//初始化状态为正常
		$scope.newDept.state = '启用';
		Meteor.call('addDept', $scope.newDept, function(error){
          if (error) {
            console.log(error);
          } else {
            $ionicHistory.goBack(-1);
          }
        });
	};

})
//部门详情
.controller('DeptDetailCtrl', function($scope,$stateParams,$state,$ionicPopup,deptService) {

	var deptsSubHandle = $scope.subscribe('departments');
	var usersSubHandle = $scope.subscribe('users');
	var employeesSubHandle = $scope.subscribe('employees');

	$scope.helpers({
		department: function() {
		  return Departments.findOne({_id:$stateParams._id});
		},
		deptUsers:function(){
			return Meteor.users.find({'profile.departments._id':$stateParams._id},{fields:{services:0}});
		},
		employees: function() {
			return Employees.find({});
		}
	});
	$scope.deptTree = deptService.getCatTree($stateParams._id);

	$scope.autorun(function(){
		if(deptsSubHandle.ready() && usersSubHandle.ready() && employeesSubHandle.ready() && $scope.deptUsers){
			// 删除非直属员工
			$scope.deptUsers.forEach(function(user,index){
				if(user.profile.departments[user.profile.departments.length-1]._id!=$stateParams._id){
					$scope.deptUsers.splice(index,1);
				}
			});
		}
	});

	$scope.delete = function(){
		var myPopup = $ionicPopup.show({
			template: '<p class="assertive">警告：删除该部门后，系统将不再统计该部门及其子部门数据。<p>',
			title: '删除部门',
			scope: $scope,
			buttons: [
			{ text: '取消' },
			{ text: '<b>确定</b>',type: 'button-royal',
				onTap: function(e) {
					Meteor.call('deleteDept', $scope.department._id, function(error){
			          if (error) {
			            console.log(error);
			          }
			          else {
			          	$state.go('app.departments');
			          }
			        });

				}
			}]
		});
	};
	$scope.update = function(){
		Meteor.call('updateDept', $scope.department, function(error){
          if (error) {
            console.log(error);
          }
          else {
          }
        });
	};
})


//仓库 / 柜组 管理
.controller('WarehousesCtrl', function($scope,$rootScope,$timeout,$ionicModal) {
	$scope.listCanSwipe = true;
	var warehousesSubHandle = $scope.subscribe('warehouses');
	var deptsSubHandle = $scope.subscribe('departments');
	// var optionsSubHandle = $scope.subscribe('default_options');

	$scope.helpers({
		warehouses: function() {
			return Warehouses.find({});
		},
		departments: function() {
		  return Departments.find({company_id:$rootScope.currentUser.profile.company_id});
		}
	});

	$ionicModal.fromTemplateUrl('templates/base/add-warehouse.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.modal = modal;
	});
	$scope.openModal = function() {
		$scope.modal.show();
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});
	$scope.$on('modal.hidden', function() {
	});
	$scope.$on('modal.removed', function() {
	});

	$scope.edit = function(store){
		$timeout(function() {
			window.location.href='#/store-'+store.name+'?isEdit=1';
		}, 200);
	};
	$scope.add = function(store){
	};
	$scope.delete = function(store){
	};
})

//仓库详情
.controller('WarehouseDetailCtrl', function($scope,$stateParams,$location) {
	var warehousesSubHandle = $scope.subscribe('warehouses');
	$scope.helpers({
		warehouseDetail: function() {
			return Warehouses.findOne({_id: $stateParams._id});
		}
	});
	$scope.isEdit=$location.search().isEdit;
	if($scope.isEdit){
		$scope.buttonText = '保存';
	}

	$scope.toggleEdit=function(){
		$scope.isEdit=!$scope.isEdit;

		if($scope.isEdit){
			$scope.buttonText = '保存';
		}else{
			$scope.buttonText = '';
		}
	};
});
